import { useState, useEffect, useCallback, useMemo } from 'react';
import { Toast } from '@douyinfe/semi-ui';
import type {
  FieldsCityListOptions,
  FieldsCityInfo,
  CurrentRowHookOptions,
  FieldsCityInfoRow
} from './types';
import {
  getFieldsCityList,
  getFieldsCityDetail,
  createFieldsCity,
  removeFieldsCity,
  updateFieldsCity,
} from '@/services/fieldsCitys';

export function useFieldsCityList(options: Partial<FieldsCityListOptions> = {}) {
  const [page, setPage] = useState(options.page ?? 1);
  const [pageSize, setPageSize] = useState(options.pageSize ?? 10);
  const [keyword, setKeyword] = useState(options.keyword ?? '');
  const [total, setTotal] = useState(0);
  const [tableLoading, setTableLoading] = useState(false);
  const [tableData, setTableData] = useState<FieldsCityInfo[]>([]);

  async function getList(
    page: number,
    pageSize: number,
    keyword: string = ''
  ) {
    setTableLoading(true);
    try {
      const { code, message, data } = await getFieldsCityList(page, pageSize, keyword);
      if (code !== 0) {
        throw new Error(message);
      }
      const { list, total } = data;
      setTableData(list);
      setTotal(total);

      setTableLoading(false);
    } catch (e) {
      Toast.error(e instanceof Error ? e.message : '获取数据失败');
    }
    setTableLoading(false);
  }

  useEffect(() => {
    getList(1, 10);
  }, []);

  const handleKeywordChange = (newKeyword: string) => {
    setKeyword(newKeyword);
  }
  
  const handlePageInfoChange = (page: number, pageSize: number) => {
    setPage(page);
    setPageSize(pageSize);
    getList(page, pageSize, keyword);
  }

  const refresh = async () => {
    getList(page, pageSize, keyword);
  }

  return {
    page,
    pageSize,
    total,
    tableLoading,
    tableData,
    keyword,

    refresh,
    setPage,
    setLoading: setTableLoading,
    getList,
    handleKeywordChange,
    handlePageInfoChange,
  };
}

export function useCurrentRow({
  refresh,
  setLoading
}: CurrentRowHookOptions) {
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [modalLoading, setModalLoading] = useState(false);
  const [currentRow, setCurrentRow] = useState<Partial<FieldsCityInfoRow>>({});

  const handleCreateClick = useCallback(() => {
    setCurrentRow({});
    setCreateModalVisible(true);
  }, []);

  const handleDetailClick = useCallback(
    async <T extends { id: string | number }> ({ id }: T) => {
      setDetailModalVisible(true);
      setModalLoading(true);
      try {
        const { code, message, data } = await getFieldsCityDetail(id);
        if (code !== 0) {
          throw new Error(message);
        }
        setCurrentRow(data);
      } catch (e) {
        Toast.error(e instanceof Error ? e.message : '获取数据失败');
      }
      setModalLoading(false);
    },
    [],
  );

  const handleEditClick = useCallback(
    async <T extends { id: string | number }> ({ id }: T) => {
      setEditModalVisible(true);

      setModalLoading(true);
      try {
        const { code, message, data } = await getFieldsCityDetail(id);
        if (code !== 0) {
          throw new Error(message);
        }
        setCurrentRow(data);
      } catch (e) {
        Toast.error(e instanceof Error ? e.message : '获取数据失败');
      }
      setModalLoading(false);
    },
    [],
  );

  const handleRemoveClick = useCallback(
    async <T extends { id: string | number }> ({ id }: T) => {
      setLoading(true);
      try {
        const { message, code } = await removeFieldsCity(id);
        if (code !== 0) {
          throw new Error(message);
        }
        Toast.success('删除成功');
        refresh();
      } catch (e) {
        Toast.error(e instanceof Error ? e.message : '删除失败');
      }
      setLoading(false);
    },
    [],
  );

  const handleCloseModal = useCallback(
    () => {
      setCurrentRow({});
      setCreateModalVisible(false);
      setDetailModalVisible(false);
      setEditModalVisible(false);
    },
    []
  );

  const handleAddCityInfo = useCallback(async (formData: Partial<FieldsCityInfo>) => {
    setLoading(true);
    try {
      const { code, message } = await createFieldsCity(formData);
      if (code !== 0) {
        throw new Error(message);
      }
      Toast.success('添加成功');
      refresh();
    } catch (e) {
      Toast.error(e instanceof Error ? e.message : '添加失败');
    }
    setLoading(false);
  }, []);

  const handleEditCityInfo = useCallback(async (formData: Partial<FieldsCityInfo>) => {
    setLoading(true);
    try {
      const { code, message } = await updateFieldsCity(formData.id, formData);
      if (code !== 0) {
        throw new Error(message);
      }
      Toast.success('编辑成功');
      refresh();
    } catch (e) {
      Toast.error(e instanceof Error ? e.message : '编辑失败');
    }
    setLoading(false);
  }, []);

  return {
    currentRow,
    modalLoading,
    createModalVisible,
    detailModalVisible,
    editModalVisible,

    handleCloseModal,
    handleCreateClick,
    handleDetailClick,
    handleEditClick,
    handleRemoveClick,
    handleAddCityInfo,
    handleEditCityInfo,
  };
}
